<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo0102-路由05-路由导航守卫</title>
</head>
<script src="../libs/vue.js"></script>
<script src="../libs/vue-router.3.5.3.js"></script>

<style>
    .container{
        width: 100%;
        min-width: 320px;
        max-width: 640px;

        margin:0 auto;
    }

    .page404 {
      color:red ;
    }
</style>
<body> 
  <div id="app">
    <div>
      <h1>HEADER</h1>
      <welcome></welcome>
    </div>
    <hr><br>
    <div>
      <router-view></router-view>
    </div>
  </div>
</body>

<script>
/*
普通：
welcome 

// 这里有个问题：若未匹配资源，全部重定向到 login ；
// 只有登录后，未匹配到时才会报 404 
404:
page404

鉴权：
login 

保护页：
dashboard
userInfo

*/

const { isNavigationFailure, NavigationFailureType } = VueRouter


const Welcome = {
  template:`<div>
      <h1>Hello ! 这里是欢迎页</h1>

      <router-link to="/dashboard"> Dashboard  </router-link>
      <router-link to="/user-info"> UserInfo  </router-link>
      <router-link to="/login"> Login </router-link>
      <hr><br>
      <button v-on:click="logout">退出登录</button>
    </div>`,
    methods:{
      logout:function(){
        sessionStorage.clear();
        // console.log();
        var currentRouteName = this.$router.currentRoute.name ;
        /*
        https://v3.router.vuejs.org/zh/guide/advanced/navigation-failures.html#导航检测故障  
        发现了新大陆。。。！！！
        {
            "redirected": 2,
            "aborted": 4,
            "cancelled": 8,
            "duplicated": 16
        }
        */
        console.log(NavigationFailureType);
        // 这是按照上述官网链接的新写法
        this.$router.push({name:'Login'}).catch(failure => {

          if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
            // 向用户显示一个小通知
            alert('已经重复导航url，请检查访问的url是否正确')
          }
        });

        // 下面这些是原写法
        // if(currentRouteName != 'Login'){
        //   // 当前url已经是login页面时，若重复push， vue-router会报错：
        //   // Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location
        //   this.$router.push({name:'Login'})
        // }
        // else do nothing 
      }
    }
}

const Page404 = {
  template:`<div class='page404'>
      <h1>您好！没有您要找的资源[ {{ inputUrl }} ]！</h1>
    </div>`,
  computed:{
    inputUrl : function(){
      console.log(this.$router.currentRoute);
      return this.$router.currentRoute.path
    }
  }
}

const Login = {
  data:function(){
    return {
      username : 'admin',
      pwd: '123456'
    }
  },
  template:`
    <div>
      <div>
        <label for="username">用户名：</label><input v-model="username" name="username" type="text" placeholder="用户名">
      </div>
      <div>
        <label for="pwd">密码：</label><input  v-model="pwd" name="pwd" type="text" placeholder="密码">
      </div>
      <div>
        <button v-on:click="dologin">登录</button>
      </div>
    </div>`,
    methods:{
      dologin:function(){
         console.log(`捕获输入的用户名：${this.username}，密码：${this.pwd}`);
         var userInfo = {username:this.username , pwd:this.pwd};

         sessionStorage.setItem('x-token',JSON.stringify(userInfo));

         this.$router.push({name:'Dashboard'})
      }
    }
};

const Dashboard = {
  template:`<div>
      <h1>Hello {{ sessionUserName }}! 这里是您的 Dashboard 页</h1>
    </div>`
    ,
  computed:{
    sessionUserName : function(){
      var tokenObj = sessionStorage.getItem('x-token');
      var userInfo = JSON.parse(tokenObj);
      return userInfo.username
    }
  }
}

const UserInfo = {
  template:`<div>
      <h1>Hello {{ sessionUser.username }}! 这里是您的 Info 页 。</h1>
      <h2>你的密码是：{{ sessionUser.pwd }}</h2>
    </div>`
    ,
  computed:{
    sessionUser : function(){
      var tokenObj = sessionStorage.getItem('x-token');
      var userInfo = JSON.parse(tokenObj);
      return userInfo
    }
  }

}

Vue.component('welcome',Welcome);


const routes = [
// {
//   path: '/',
//   component: Welcome,
//   name:'Welcome'
// },
{
  path: '/dashboard',
  component: Dashboard,
  name:'Dashboard'
},
{
  path: '/user-info',
  component: UserInfo,
  name:'UserInfo'
},

// 倒数第2，给login
{
  path: '/login',
  component: Login,
  name:'Login'
},
// 最后一个 * 重定向给 404
{
  path: '*',
  component: Page404,
  name:'Page404'
}
]

const router = new VueRouter({
  routes 
});

router.beforeEach((to, from, next) => {

  var isAuthenticated = false;
  var userInfo = null;

  var tokenObj = sessionStorage.getItem('x-token');
  // console.log(`登录用户信息：${tokenObj}`);
  if (tokenObj){
    userInfo = JSON.parse(tokenObj);
  // console.log(`登录用户 解析 信息：${userInfo}`);
    if(userInfo){
      isAuthenticated = true;
    }
  }

  console.log(`是否已登录 , isAuthenticated : ${isAuthenticated}`);

  if(to.name == 'Login' && isAuthenticated){
    // 若已登录，但手工访问login，则直接返回dashboard页
    next({ name: 'Dashboard' })
  } else if (to.name !== 'Login' && !isAuthenticated) {
    // 若未登录，且未授权，则重定向到login页
    next({ name: 'Login' })
  }  else if (from.name =='Login' && to.name == 'Login' ) {
    // 奇葩：源和目的 都为login，直接取消掉。。。
    // Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location
    // 这里放return 也没用。 router直接报错
    return ;
  } else {
    next()
  }
});

const app = new Vue({
  router
}).$mount('#app');

</script>
</html>